package d512a.TAKO;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.net.ParseException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.client.android.CaptureActivity;

import d512a.TAKO.helpers.DataBaseHelper;
import d512a.TAKO.helpers.DateHelper;

public class RecommenedProductsActivity extends ListActivity {
	private LayoutInflater mInflater;
	private Vector<RowData> data;
	private DataBaseHelper foodDB;
	private String scanningsID;
	private String recommend_idPrimKey;
	RowData rd;
	private String[] foodIds = new String[] {};
	private String[] productName = new String[] {};
	private String[] ratingValue = new String[] {};

	private class RowData {
		protected String mFoodId;
		protected String mProductName;
		protected String mRatingValue;

		RowData(String foodId, String productName, String ratingValue) {
			mFoodId = foodId;
			mProductName = productName;
			mRatingValue = ratingValue;
		}

		@Override
		public String toString() {
			return mFoodId + " " + mProductName + " " + mRatingValue;
		}
	}

	private class CustomAdapter extends ArrayAdapter<RowData> {
		public CustomAdapter(Context context, int resource, int textViewResourceId,
				List<RowData> objects) {
			super(context, resource, textViewResourceId, objects);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			TextView productName = null;
			// TextView ratingValue = null;
			ImageView img = null;
			RowData rowData = getItem(position);
			if (null == convertView) {
				convertView = mInflater.inflate(R.layout.recommendation_list, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}
			holder = (ViewHolder) convertView.getTag();
			productName = holder.getProductName();
			productName.setText(rowData.mProductName);
			// r = holder.getRelativeLayout();
			img = holder.getImgRating();
			switch(Integer.parseInt(rowData.mRatingValue)) {
			case 1:
			    img.setImageResource(R.drawable.spis_mest);
			    break;
			case 2: 
			    img.setImageResource(R.drawable.spis_mindre);
			    break;
		    default:
		        img.setImageResource(R.drawable.spis_mindst);
		        break;
			}
			
			// img.setBackgroundDrawable(getResources().getDrawable(
			// ColorHelper.getColor(Integer.parseInt(rowData.mRatingValue))));
			// ratingValue = (TextView) ((ViewGroup) r).getChildAt(1);
			// ratingValue.setText(rowData.mRatingValue);
			return convertView;
		}

		private class ViewHolder {
			private View mRow;
			private TextView productName = null;
			private ImageView imgRating = null;
//			private RelativeLayout rel = null;

			public ViewHolder(View row) {
				mRow = row;
			}

			public TextView getProductName() {
				if (null == productName) {
					productName = (TextView) mRow.findViewById(R.id.txtProductName);
				}
				return productName;
			}

			public ImageView getImgRating() {
			    if (null == imgRating) {
			        imgRating = (ImageView) mRow.findViewById(R.id.imgRating);
                }
                return imgRating;
			}
//			public RelativeLayout getRelativeLayout() {
//				if (null == rel) {
//					rel = (RelativeLayout) mRow.findViewById(R.id.relLayout);
//				}
//				return rel;
//			}
		}
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		data = new Vector<RowData>();

		handleDatabase();
		String foodId = getIntent().getExtras().getString("foodId");
		if (ProductTabWidgetActivity.fromScan == true) {
			scanningsID = getIntent().getExtras().getString("scanningsID");
		}
		
		getRecommendedProducts(foodId);

		for (int i = 0; i < productName.length; i++) {
			try {
				rd = new RowData(foodIds[i], productName[i], ratingValue[i]);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			data.add(rd);
		}

		CustomAdapter adapter = new CustomAdapter(this, R.layout.recommendation_list,
				R.id.txtProductName, data);
		setListAdapter(adapter);
		getListView().setTextFilterEnabled(true);
	}

	private void handleDatabase() {
		foodDB = new DataBaseHelper(this);

		try {
			foodDB.openDataBase();
		} catch (SQLException sqle) {
			throw sqle;
		} finally {
			foodDB.close();
		}
	}

	public void onListItemClick(ListView parent, View v, int position, long id) {
	    Intent intent = new Intent(RecommenedProductsActivity.this, ProductTabWidgetActivity.class);
        intent.putExtra("foodId", foodIds[position]);
        intent.putExtra("scanningsID", scanningsID);
		
		// insert in Recommended table
		Cursor cursor = foodDB.getProductName_id(foodIds[position]);
		if (cursor.getCount() > 0) {
			cursor.moveToFirst(); 
			int primKeyId = cursor.getInt(0);
			String date = DateHelper.getDate();
			if (ProductTabWidgetActivity.fromScan == true) {
				Cursor c = foodDB.insertInRecommended(primKeyId, null, scanningsID, 1, date);
				c.moveToFirst();
				intent.putExtra("rec_id", c.getString(0));
				c.close();
			} else {
				// Get lastly inserted _id in the Recommended table
				Cursor cursor2 = foodDB.getRecommendedPrimKey_id();
				cursor2.moveToFirst();
				recommend_idPrimKey = cursor2.getString(0);
                cursor2.close();
                Cursor c = foodDB.insertInRecommended(primKeyId, recommend_idPrimKey, null, 1, date);
                c.moveToFirst();
	            intent.putExtra("rec_id", c.getString(0));
	            c.close();
			}
		}
        cursor.close();
		
		ProductTabWidgetActivity.fromScan = false;
		startActivity(intent);
	}

	private void getRecommendedProducts(String foodId) {
		Cursor cursor = foodDB.getRecommendedProductsInCategory3(foodId);
		if (cursor.getCount() > 0) {
			ArrayList<String> listFoodIds = new ArrayList<String>();
			ArrayList<String> listProductNames = new ArrayList<String>();
			ArrayList<String> listRatingValues = new ArrayList<String>();
			while (cursor.moveToNext()) {
				String food_id = cursor.getString(0);
				String productName = cursor.getString(1);
				String rating = cursor.getString(2);
				listFoodIds.add(food_id);
				listProductNames.add(productName);
				listRatingValues.add(rating);
			}
			foodIds = listFoodIds.toArray(new String[listFoodIds.size()]);
			productName = listProductNames.toArray(new String[listProductNames.size()]);
			ratingValue = listRatingValues.toArray(new String[listRatingValues.size()]);
		} else {
			Toast.makeText(RecommenedProductsActivity.this, "Ingen bedre alternativer fundet.",
					Toast.LENGTH_LONG).show();
			finish();
		}
        cursor.close();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.product_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		Intent i;
		switch (item.getItemId()) {
		case R.id.menu_item_scan:
			startBarcodeScanner();
			return true;
		case R.id.menu_item_home:
			i = new Intent(getApplicationContext(), HomescreenActivity.class);
			startActivity(i);
			return true;
		case R.id.menu_item_shoppingBasket:
			i = new Intent(getApplicationContext(), BasketActivity.class);
			startActivity(i);
			return true;
		case R.id.menu_item_settings:
			i = new Intent(getApplicationContext(), UserInfoActivity.class);
			startActivity(i);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void startBarcodeScanner() {
		Intent i = new Intent(getApplicationContext(), CaptureActivity.class);
		startActivity(i);
	}
}
